<template>
  <div class="subject-edit">
    <el-card>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="160px"
        style="max-width: 600px; margin: 0 auto"
      >
        <el-form-item label="学科名称" prop="name">
          <el-input v-model="form.name" maxlength="100" placeholder="请输入学科名称" />
        </el-form-item>

        <el-form-item label="年级" prop="level">
          <el-select v-model="form.level" placeholder="请选择年级">
            <el-option
              v-for="(label, value) in levelMap"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSubmit">提交</el-button>
          <el-button :disabled="loading" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import UserAPI from "@/api/system/user.api";
import { ElMessage } from "element-plus";

// 年级映射：1-6 小学，7-9 初中，10-12 高中
const levelMap: Record<number, string> = {
  1: "一年级",
  2: "二年级",
  3: "三年级",
  4: "四年级",
  5: "五年级",
  6: "六年级",
  7: "初一",
  8: "初二",
  9: "初三",
  10: "高一",
  11: "高二",
  12: "高三",
};

const route = useRoute();
const router = useRouter();
const formRef = ref();
const loading = ref(false);
const isEdit = computed(() => !!route.query.id);

const form = reactive({
  id: null as number | null,
  name: "",
  level: undefined as number | undefined,
});

const rules = {
  name: [{ required: true, message: "请输入学科名称", trigger: "blur" }],
  level: [{ required: true, message: "请选择年级", trigger: "change" }],
};

// 获取学科详情
async function fetchDetail(id: number) {
  loading.value = true;
  try {
    const res: any = await UserAPI.getSubjectDetail(id);
    const data = res;

    if (data) {
      form.id = data.id ?? id;
      form.name = data.name ?? "";
      form.level = data.level;
    }
  } catch {
    ElMessage.error("获取学科详情失败");
  } finally {
    loading.value = false;
  }
}

function handleSubmit() {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) return;
    loading.value = true;

    const payload: any = {
      name: form.name,
      level: form.level,
      levelName: levelMap[form.level as number],
    };

    // 如果是编辑，添加id
    if (isEdit.value && form.id) {
      payload.id = form.id;
    }

    UserAPI.editSubject(payload)
      .then(() => {
        ElMessage.success(isEdit.value ? "编辑成功" : "添加成功");
        router.back();
      })
      .catch(() => {
        ElMessage.error(isEdit.value ? "编辑失败" : "添加失败");
      })
      .finally(() => {
        loading.value = false;
      });
  });
}

function handleReset() {
  if (isEdit.value && form.id) {
    fetchDetail(form.id);
  } else {
    Object.assign(form, {
      id: null,
      name: "",
      level: undefined,
    });
  }
}

onMounted(() => {
  const id = Number(route.query.id);
  if (id) {
    form.id = id;
    fetchDetail(id);
  }
});
</script>

<style scoped lang="scss">
.subject-edit {
  padding: 32px 0;
}
</style>
